/*
 * FrmMain.java
 *
 * Created on November 18, 2007, 8:09 PM
 */

package com.piu.frm;

import com.google.gdata.client.*;
import com.google.gdata.client.calendar.*;
import com.google.gdata.data.*;
import com.google.gdata.data.extensions.*;
import com.google.gdata.data.photos.AlbumEntry;
import com.google.gdata.util.*;
import java.io.File;
import java.io.FilenameFilter;
import java.util.List;
import javax.swing.SwingWorker;
import com.piu.lib.Album;
import com.piu.lib.Credentials;

/**
 *
 * @author  Spiros Gezerlis
 */
public class FrmMain extends javax.swing.JFrame {
    /** Creates new form FrmMain */
    public FrmMain() {
        initComponents();
    }
   
    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        choose = new javax.swing.JFileChooser();
        txtUser = new javax.swing.JTextField();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        txtPass = new javax.swing.JPasswordField();
        jLabel3 = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        lstAlbums = new javax.swing.JList();
        btnLsAlbums = new javax.swing.JButton();
        lblReport = new javax.swing.JLabel();
        txtPath = new javax.swing.JTextField();
        btnUpload = new javax.swing.JButton();
        jButton3 = new javax.swing.JButton();
        jPanel1 = new javax.swing.JPanel();
        txtNewAlbum = new javax.swing.JTextField();
        btnAddAlbum = new javax.swing.JButton();
        prg = new javax.swing.JProgressBar();
        lblPreview = new javax.swing.JLabel();

        choose.setFileSelectionMode(javax.swing.JFileChooser.DIRECTORIES_ONLY);

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("PiU: Picasa Uploader");

        jLabel1.setText("Username");

        jLabel2.setText("Password");

        jLabel3.setText("@gmail.com");

        lstAlbums.setBorder(javax.swing.BorderFactory.createTitledBorder("..."));
        lstAlbums.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
        lstAlbums.setLayoutOrientation(javax.swing.JList.VERTICAL_WRAP);
        jScrollPane1.setViewportView(lstAlbums);

        btnLsAlbums.setText("List Albums");
        btnLsAlbums.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnLsAlbumsActionPerformed(evt);
            }
        });

        lblReport.setForeground(new java.awt.Color(204, 0, 0));
        lblReport.setHorizontalAlignment(javax.swing.SwingConstants.TRAILING);

        txtPath.setEditable(false);
        txtPath.setText("/home/spiros/Desktop");

        btnUpload.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/piu/images/up.png"))); // NOI18N
        btnUpload.setToolTipText("<html>Upload (/\\) folder pictures<br>to selected Album(\\/)");
        btnUpload.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnUploadActionPerformed(evt);
            }
        });

        jButton3.setText("...");
        jButton3.setToolTipText("Select folder to upload");
        jButton3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton3ActionPerformed(evt);
            }
        });

        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder("Add new album"));

        btnAddAlbum.setText("<< Add");
        btnAddAlbum.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnAddAlbumActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(txtNewAlbum, javax.swing.GroupLayout.DEFAULT_SIZE, 104, Short.MAX_VALUE)
                    .addComponent(btnAddAlbum, javax.swing.GroupLayout.Alignment.TRAILING))
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(txtNewAlbum, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(btnAddAlbum)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        prg.setStringPainted(true);

        lblPreview.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        lblPreview.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 163, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addGroup(layout.createSequentialGroup()
                                .addGap(12, 12, 12)
                                .addComponent(btnLsAlbums)))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(lblPreview, javax.swing.GroupLayout.PREFERRED_SIZE, 128, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel2)
                            .addComponent(jLabel1))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(txtUser)
                            .addComponent(txtPass, javax.swing.GroupLayout.DEFAULT_SIZE, 126, Short.MAX_VALUE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jLabel3)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(btnUpload)
                        .addGap(17, 17, 17)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(prg, javax.swing.GroupLayout.DEFAULT_SIZE, 346, Short.MAX_VALUE)
                            .addComponent(lblReport, javax.swing.GroupLayout.DEFAULT_SIZE, 346, Short.MAX_VALUE)))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addComponent(txtPath, javax.swing.GroupLayout.DEFAULT_SIZE, 398, Short.MAX_VALUE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jButton3)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(txtUser, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel3))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(txtPass, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButton3)
                    .addComponent(txtPath, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addGap(14, 14, 14)
                        .addComponent(prg, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(lblReport, javax.swing.GroupLayout.PREFERRED_SIZE, 19, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(layout.createSequentialGroup()
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(btnUpload, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                        .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                            .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(btnLsAlbums))
                        .addComponent(lblPreview, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.PREFERRED_SIZE, 128, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 131, Short.MAX_VALUE))
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents
    
    private void btnUploadActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnUploadActionPerformed
        new SwingWorker() {
            protected Object doInBackground() throws Exception {
                btnUpload.setEnabled(false);
                try {
                    if(new File(txtPath.getText()).isDirectory() && !lstAlbums.isSelectionEmpty()){
                        File dir = new File(txtPath.getText());
                        FilenameFilter filter = new FilenameFilter() {
                            public boolean accept(File dir, String name) {
                                return name.endsWith(".jpg") || name.endsWith(".JPG");
                            }
                        };
                        String[] children = dir.list(filter);
                        
                        Credentials creds = new Credentials(txtUser.getText(),new String(txtPass.getPassword()));
                        Album album = new Album(creds);
                        
                        for (int i = 0; i < children.length; i++) {
                            String al = new String((String) lstAlbums.getSelectedValue()).replaceAll(" ","_");
                            String f = dir.getAbsolutePath()+File.separator+children[i];
                            lblReport.setText("Adding: ("+String.valueOf(i+1)+"/"+String.valueOf(children.length)+") "+children[i]);
                            lblPreview.setText("<html><img  width=128  height=128 src=\"file:"+f+"\"/>");
                            boolean added = album.addPictures(new File[]{new File(f)}, al);
                            prg.setValue(((i+1)*100)/children.length);
                            lblReport.setText(children[i] +" added: "+String.valueOf(added));
                        }
                        
                        lblReport.setText("Uploaded "+String.valueOf(children.length)+" picture(s)");
                    }else{
                        lblReport.setText("Path does not contain jpg or album not selected");
                        btnLsAlbums.doClick();
                    }
                } catch (Exception e) {
                 e.printStackTrace();   
                }
                lblPreview.setText("");
                btnUpload.setEnabled(true);
                return null;
            }
        }.execute();
    }//GEN-LAST:event_btnUploadActionPerformed
    
    private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed
        new SwingWorker() {
            protected Object doInBackground() throws Exception {
                choose.showOpenDialog(null);
                
                try {
                    txtPath.setText(choose.getSelectedFile().getAbsolutePath());
                } catch (Exception e) {
                    
                }
                return null;
            }
        }.execute();
    }//GEN-LAST:event_jButton3ActionPerformed
    
    private void btnAddAlbumActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAddAlbumActionPerformed
        new Thread(new Runnable() {
            public void run() {
                String text = btnAddAlbum.getText();
                txtNewAlbum.setEnabled(false);
                btnAddAlbum.setEnabled(false);
                btnAddAlbum.setText("Please wait...");
                try {
                    Credentials creds = new Credentials(txtUser.getText(),new String(txtPass.getPassword()));
                    Album album = new Album(creds);
                    if(album.exists(txtNewAlbum.getText().replaceAll(" ","_"))){
                        lblReport.setText("Album exists!");
                    }else{
                        if(album.addNew(txtNewAlbum.getText().replaceAll(" ","_"),Album.UNLISTED)){
                            lblReport.setText("Added album successfully!Reloading album list");
                            btnLsAlbums.doClick();
                        }
                    }
                } catch (Exception e) {
                    
                }
                btnAddAlbum.setEnabled(true);
                txtNewAlbum.setEnabled(true);
                btnAddAlbum.setText(text);
            }}).start();
    }//GEN-LAST:event_btnAddAlbumActionPerformed
    
    private void btnLsAlbumsActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnLsAlbumsActionPerformed
        new SwingWorker() {
            protected Object doInBackground() throws Exception {
                String text = btnLsAlbums.getText();
                btnLsAlbums.setEnabled(false);
                btnLsAlbums.setText("Please wait...");
                try {
                    Credentials creds = new Credentials(txtUser.getText(),new String(txtPass.getPassword()));
                    Album album = new Album(creds);
                    List<AlbumEntry> lst = album.getAlbums();
                    int lim = 0;
                    if(lst.size()>10){
                        lim=10;
                        lstAlbums.setBorder(javax.swing.BorderFactory.createTitledBorder("Viewing latest 10 albums"));
                    }else{
                        lim = lst.size();
                        lstAlbums.setBorder(javax.swing.BorderFactory.createTitledBorder("Viewing "+String.valueOf(lim)+" albums"));
                    }
                    final String[] astrings=new String[lim];
                    for(int i=0;i<lim;i++){
                        astrings[i]=lst.get(i).getTitle().getPlainText();
                    }
                    lstAlbums.setModel(new javax.swing.AbstractListModel() {
                        String[] strings = astrings;
                        public int getSize() { return strings.length; }
                        public Object getElementAt(int i) { return strings[i]; }
                    });
                } catch (Exception e) {
                    e.printStackTrace();
                    lblReport.setText("Check credentials!");
                }
                lblReport.setText("");
                btnLsAlbums.setEnabled(true);
                btnLsAlbums.setText(text);
                return null;
            }
        }.execute();
    }//GEN-LAST:event_btnLsAlbumsActionPerformed
    
    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new FrmMain().setVisible(true);
            }
        });
    }
    
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnAddAlbum;
    private javax.swing.JButton btnLsAlbums;
    private javax.swing.JButton btnUpload;
    private javax.swing.JFileChooser choose;
    private javax.swing.JButton jButton3;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JLabel lblPreview;
    private javax.swing.JLabel lblReport;
    private javax.swing.JList lstAlbums;
    private javax.swing.JProgressBar prg;
    private javax.swing.JTextField txtNewAlbum;
    private javax.swing.JPasswordField txtPass;
    private javax.swing.JTextField txtPath;
    private javax.swing.JTextField txtUser;
    // End of variables declaration//GEN-END:variables
    
}
